const { UserComponent, ResponseComponent } = require('../components');

/**
 * 用户控制器
 * 处理用户相关的HTTP请求
 */
class UserController {
  
  /**
   * 创建用户
   */
  static async create(req, res) {
    try {
      const result = await UserComponent.createUser(req.body);
      return ResponseComponent.handleComponentResult(res, result, 201);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }

  /**
   * 获取用户列表
   */
  static async getList(req, res) {
    try {
      const options = {
        page: parseInt(req.query.page) || 1,
        limit: parseInt(req.query.limit) || 10,
        username: req.query.username,
        role: req.query.role
      };
      
      const result = await UserComponent.getUserList(options);
      return ResponseComponent.handleComponentResult(res, result);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }

  /**
   * 根据ID获取用户
   */
  static async getById(req, res) {
    try {
      const { id } = req.params;
      const result = await UserComponent.getUserById(id);
      return ResponseComponent.handleComponentResult(res, result);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }

  /**
   * 更新用户
   */
  static async update(req, res) {
    try {
      const { id } = req.params;
      const result = await UserComponent.updateUser(id, req.body);
      return ResponseComponent.handleComponentResult(res, result);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }

  /**
   * 删除用户
   */
  static async delete(req, res) {
    try {
      const { id } = req.params;
      const result = await UserComponent.deleteUser(id);
      return ResponseComponent.handleComponentResult(res, result);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }

  /**
   * 批量删除用户
   */
  static async batchDelete(req, res) {
    try {
      const { ids } = req.body;
      const result = await UserComponent.batchDeleteUsers(ids);
      return ResponseComponent.handleComponentResult(res, result);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }

  /**
   * 用户登录
   */
  static async login(req, res) {
    try {
      const { username, password } = req.body;
      const result = await UserComponent.authenticateUser(username, password);
      return ResponseComponent.handleComponentResult(res, result);
    } catch (error) {
      return ResponseComponent.internalError(res, error);
    }
  }
}

module.exports = UserController;